#!/usr/bin/env python
# -*- coding: utf-8 -*-

'''eof
name:未结清信贷笔数
code:UnsettledLoanNum
tableName:
columnName:
groups:企业征信
dependencies:IC_DSJ_2D
type:常用指标
dataSourceType:在线指标
description:
eof'''


'''
ECRSummaryECRSummaryUnsettled02:未结清信贷信息概要（7类信贷业务） list

LoanType ：业务类型 包括7类
Concernedsum_Number:关注类汇总（笔数）
Badsum_Number:不良类汇总（笔数）
Normalsum_Number:正常类汇总（笔数）

'''

import sys
import pandas as pd
import datetime
import  json

reload(sys)
sys.setdefaultencoding('utf-8')

#如果这个字段存在 但是里面的list长度为0 不包含任何dict 应该返回缺失值 不应该为0

def FormatData(tableName):
    try:
        ecr = json.loads(EC[0]["ecr"])[tableName]
        return ecr if isinstance(ecr, list) and len(ecr) > 0 else [{}]
    except:
        return [{}]

def UnsettledLoanNum():
    null_type_list = ['', None, 'null', 'Null', 'NULL', '/', ' ']
    concernedsum_num = [] #关注类汇总
    badsum_num = [] #不良类汇总
    normalsum_num = [] #正常类汇总

    try:
        ECRSummaryUnsettled02 = FormatData('ECRSummaryUnsettled02')
        
        if ECRSummaryUnsettled02 == [{}]:
            return u'缺失值'

        else:
            if len(ECRSummaryUnsettled02) >= 1:
                for i in ECRSummaryUnsettled02:
                    #关注类笔数
                    if i.has_key('Concernedsum_Number') \
                            and i['Concernedsum_Number'] not in null_type_list\
                            and isfloat(i['Concernedsum_Number']):
                        concernedsum_num.append(float(i['Concernedsum_Number']))
                    #不良类笔数
                    if i.has_key('Badsum_Number') \
                            and i['Badsum_Number'] not in null_type_list \
                            and isfloat(i['Badsum_Number']):
                        badsum_num.append(float(i['Badsum_Number']))
                    #正常类比数
                    if i.has_key('Normalsum_Number') \
                            and i['Normalsum_Number'] not in null_type_list\
                            and isfloat(i['Normalsum_Number']):
                        normalsum_num.append(float(i['Normalsum_Number']))
                #7类业务，关注，不良，正常总笔数相加
                all_num = sum(concernedsum_num) + sum(badsum_num) + sum(normalsum_num)
                return all_num
            else:
                return u'缺失值'
    except:
        return u'缺失值'

def isfloat(x):
    try:
        if isinstance(float(x), float) and float(x)>=0:
            return True
        else:
            return False
    except:
        return False


result = UnsettledLoanNum()